package com.cuit.jifver.weibo.activity;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cuit.jifver.weibo.activity.WebViewAct.JavaScriptInterface;
import com.cuit.jifver.weibo.data.ConfigUtil;
import com.cuit.jifver.weibo.data.Weibo;
import com.cuit.jifver.weibo.data.WeiboException;
import com.cuit.jifver.weibo.net.RequestToken;
import com.cuit.jifver.weibo.net.Utility;
import com.cuit.jifver.weibo.util.Constants;
import com.cuit.jifver.weibo.util.TextUtil;

import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;



/**
 * 用户授权页面 1.初始化OAuth对象 2.获取用户授权页面并填充至webView 3.根据载入的url判断匹配规则的结果执行跳转
 * 
 * @author bywyu
 * 
 */
public class AuthorizationAct extends Activity
{
	
	private static final String TAG = "AuthorizationAct";;

	private final String LOGTAG = "AuthorizationAct";
	
	private WebView authorizationView;
	
	Weibo mWeibo = Weibo.getInstance();
	ConfigUtil configUtil = ConfigUtil.getInstance();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shared_authorization_ui);
		
		Weibo weibo = Weibo.getInstance();
//		System.out.println("AppKey="+mWeibo.APP_KEY);
//		System.out.println("AppSecret="+mWeibo.APP_SECRET);
//		System.out.println("URL_OAUTH_TOKEN="+mWeibo.URL_OAUTH_TOKEN);
//		System.out.println("URL_AUTHORIZE="+mWeibo.URL_AUTHORIZE);
//		System.out.println("URL_ACCESS_TOKEN="+mWeibo.URL_ACCESS_TOKEN);
		Uri uri = null;
		try {

			Log.e(TAG, "callBackUrl--A->"+ConfigUtil.callBackUrl);
			RequestToken requestToken = weibo.getRequestToken(AuthorizationAct.this, Weibo.APP_KEY, Weibo.APP_SECRET, ConfigUtil.callBackUrl);
			System.out.println("进入requesttoken");
			Log.e(TAG, "callBackUrl--B-->"+ConfigUtil.callBackUrl);
			uri = Uri.parse(Weibo.URL_AUTHORIZE + "?oauth_token=" + requestToken.getToken());
		} catch (WeiboException e) {
			e.printStackTrace();
			System.out.println("出现异常");
		}
		// Log.d(LOGTAG, "onCreat() [Authoriz] url = "+url);
		Log.e("", "onCreat() [Authoriz] url =" + uri);
		if (uri == null) {
			Toast.makeText(this, "获取RequestToken出错", Toast.LENGTH_SHORT).show();
			this.finish();
		}
       else
		{
				initWebView(uri.toString());
		}
		
	}
	
	private void initWebView(String url) {
		authorizationView = (WebView) findViewById(R.id.authorizationView);
		authorizationView.clearCache(true);
		authorizationView.getSettings().setJavaScriptEnabled(true);
		authorizationView.getSettings().setSupportZoom(true);
		authorizationView.getSettings().setBuiltInZoomControls(true);
		authorizationView.setWebViewClient(new WebViewC());
		Log.e(TAG, "callBackUrl--C-->"+ConfigUtil.callBackUrl);
		authorizationView.loadUrl(url);
		
		//绑定java对象到JavaScript中，这样就能在JavaScript中调用java对象，实现通信。   
	    //这种方法第一个参数就是java对象，第二个参数表示java对象的别名，在JavaScript中使用   
	    authorizationView.addJavascriptInterface(new JavaScriptInterface(), "Methods");  
	}
	
	class WebViewC extends WebViewClient
	{
		private int index = 0;
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			
			view.loadUrl(url);
			Log.e(TAG, "callBackUrl--D-->"+ConfigUtil.callBackUrl);
			return true;
		}
		
		/**
		 * 由于腾讯授权页面采用https协议 执行此方法接受所有证书
		 */
		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			System.out.println("onReceivedSslError(WebView view, SslErrorHandler handler, SslError error)");
			handler.proceed();
		}
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			Log.d(LOGTAG, "onPageStarted url = " + url);
			
			/**
			 * url.contains(ConfigUtil.callBackUrl) 如果授权成功url中包含之前设置的callbackurl
			 * 包含：授权成功
			 * 
			 * index == 0 由于该方法onPageStarted可能被多次调用造成重复跳转 则添加此标示
			 */
			Log.e(TAG, "xiao_url="+url);
			if (url.contains(configUtil.getVerifierName()+"=") && index == 0) {
				Log.e(TAG, "callBackUrl--E-->"+configUtil.getVerifierName());
				index++;
				Intent intent = new Intent(AuthorizationAct.this, ShowAccessTokenAct.class);
				intent.putExtra(ConfigUtil.OAUTH_VERIFIER_URL, url);
				AuthorizationAct.this.startActivity(intent);
				AuthorizationAct.this.finish();
			}
		}
		
		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			 view.loadUrl("javascript:window.Methods.getHTML('<head>'+document.getElementsByTagName('body')[0].innerHTML+'</head>');"); 
			super.onPageFinished(view, url);
		}
		
		
	}
	
	 class JavaScriptInterface  
	    {  

	      public void getHTML(String html)  
	      {  

	           String verifier = getVerifier(html);  
	           if (!TextUtil.isEmpty(verifier) && configUtil.getCurWeibo().equals(ConfigUtil.WANGYIW))  
	           {   
	              Intent intent = new Intent();
	              intent.setClass(AuthorizationAct.this, ShowAccessTokenAct.class);
	              AuthorizationAct.this.startActivity(intent);
	              AuthorizationAct.this.finish();
	              
	          }  
	     }  
	      
	      
	      
	      public String getVerifier(String html)  
			{
				String ret = "";
				String regEx = "You have successfully authorized";
				Pattern p = Pattern.compile(regEx);
				Matcher m = p.matcher(html);
				boolean result = m.find();
				if (result)
				{
					if (configUtil.getCurWeibo().equals(ConfigUtil.WANGYIW))
					{
						ret = "success";
					}

				}
				return ret;
			}  
		  }  
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (authorizationView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		{
			authorizationView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
}
























